﻿using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using JwtToken.Redis.WebApi.Dto;
using JwtToken.Redis.WebApi.Models;
using Microsoft.IdentityModel.Tokens;

namespace JwtToken.Redis.WebApi.Tools
{
    /// <summary>
    /// jwt辅助类
    /// </summary>
    public class JwtTokenHelper
    {
        public static string CreatToken(JwtSettings _jwtSettings, LoginDataDto dataDto)
        {
            var claim = new Claim[]{
                    new Claim(ClaimTypes.Name,dataDto.UserName),
                    new Claim(ClaimTypes.Role,dataDto.UserRoleName)
                };

            //对称秘钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
            //签名证书(秘钥，加密算法)
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //生成token  [注意]需要nuget添加Microsoft.AspNetCore.Authentication.JwtBearer包，并引用System.IdentityModel.Tokens.Jwt命名空间
            var token = new JwtSecurityToken(
                _jwtSettings.Issuer,
                _jwtSettings.Audience,
                claim,
                DateTime.Now,
                DateTime.Now.AddMinutes(1),
                creds);

            string EncodeToken = new JwtSecurityTokenHandler().WriteToken(token);
            return EncodeToken;

        }
    }
}
